package org.yylnb.openplatform.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.yylnb.openplatform.commons.utlis.CommonsResult;
import org.yylnb.openplatform.gateway.api.CacheService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 当前过滤器主要作用是针对有幂等性要求的服务进行幂等性判断
 *
 * @author RainLin
 * @date 2020/7/25 - 19:46
 */
@Component
public class IdempotentFilter extends ZuulFilter {

    private final ObjectMapper objectMapper;

    private final CacheService cacheService;

    public IdempotentFilter(CacheService cacheService, ObjectMapper objectMapper) {
        this.cacheService = cacheService;
        this.objectMapper = objectMapper;
    }

    @Override
    public String filterType() {
        //前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 86;
    }

    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //如果前置过滤器拦截了,当前过滤器不启用,如果请求是一个非幂等的,当前过滤器也不启用,所以会有多个判断条件,只有全部都符合才启用
        HttpServletRequest request = context.getRequest();
        //这个就是标记,类似于学号
        String method = request.getParameter("method");
        return false;
    }

    @Override
    public Object run() {
        //获取到当前请求的签名
        RequestContext context = RequestContext.getCurrentContext();
        //获取当前请求在前面保存的签名
        String sign = (String) context.get("sign");
        //查询签名是否存在过,也就是说我们一定在某个地方保存了签名,我们分析发现实际上可以直接使用sign做为key在redis中随便放个数据
        //需要判断的时候只需要用签名获取一次数据,能获取到就代表签名是存在的
        Map<String, String> map = null;
        map = (Map<String, String>) cacheService.get(sign).getData();
        //获取签名key真正的对应的数据
        String data = map.get("data");
        if (StringUtils.isEmpty(data)) {
            //不存在,代表没有请求过,直接把数据放到redis中一份
            //过期时间和时间戳的有效期保持一致即可,因为时间戳只要变了,就一定会发起新请求
            cacheService.set(sign, "DASDASDASDASDASD", 60L);
        } else {
            //代表请求已经存在了,拦截请求
            context.setSendZuulResponse(false);
            HttpServletResponse response = context.getResponse();
            response.setContentType("application/json;charset=utf-8");
            try {
                context.setResponseBody(objectMapper.writeValueAsString(CommonsResult.ERROR.msg("当前请求不允许刷新")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }
}
